package org.thiki.repository;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.thiki.domain.Customer;

/**
 * @author trisberg
 */
@Repository
@Transactional(propagation = Propagation.SUPPORTS)
public class CustomerRepositoryImpl extends HibernateDaoSupport implements CustomerRepository {
	
	/*
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.em = entityManager;
    }
	*/

    public Customer findById(Long id) {
        // Customer c =  em.find(Customer.class,id);
    	Customer c = (Customer) getHibernateTemplate().get(Customer.class, id);
        // to avoid lazy load issue - make sure all orders are loaded
        if (c != null && c.getOrders() != null && c.getOrders().size() > 0) {
            c.getOrders().iterator();
        }
        return c;
    }

    public void add(Customer customer) {
//        em.persist(customer);
    	getHibernateTemplate().save(customer);
    }

    public Customer merge(Customer customer) {
//        return em.merge(customer);
    	return (Customer) getHibernateTemplate().merge(customer);
    }

    public List<Customer> findAll() {
//        return em.createQuery("select c from Customer c")
//                .getResultList();
    	return getHibernateTemplate().find("from Customer c");
    }
}
